import * as fs from 'fs';
import * as path from 'path';
import { Logger } from '../../src/logger/Logger';

/**
 * OpenHarmony 代码库索引器
 * 扫描OHCode目录，学习并索引代码模式
 */
export class CodebaseIndexer {
    private ohCodeRoot: string;
    private knowledgeBase: CodeKnowledgeBase;
    
    constructor(ohCodeRoot: string) {
        this.ohCodeRoot = ohCodeRoot;
        this.knowledgeBase = new CodeKnowledgeBase();
    }

    /**
     * 执行完整的代码库学习
     */
    public async learnCodebase(): Promise<void> {
        Logger.info('[CodebaseIndexer] 开始学习 OHCode 代码库...');
        const startTime = Date.now();

        // 1. 扫描所有 OH 工程
        const projects = await this.scanOHProjects();
        Logger.info(`[CodebaseIndexer] 发现 ${projects.length} 个 OH 工程`);

        // 2. 学习每个工程的模式
        for (const project of projects) {
            await this.learnProject(project);
        }

        // 3. 提取通用模式
        await this.extractCommonPatterns();

        // 4. 构建索引
        await this.buildIndex();

        // 5. 持久化知识库
        await this.saveKnowledgeBase();

        const duration = Date.now() - startTime;
        Logger.info(`[CodebaseIndexer] 学习完成，耗时: ${duration}ms`);
        this.printSummary();
    }

    /**
     * 扫描OHCode目录下的所有OH工程
     */
    private async scanOHProjects(): Promise<OHProject[]> {
        const projects: OHProject[] = [];
        
        if (!fs.existsSync(this.ohCodeRoot)) {
            Logger.warn(`[CodebaseIndexer] OHCode 目录不存在: ${this.ohCodeRoot}`);
            return projects;
        }

        const entries = fs.readdirSync(this.ohCodeRoot, { withFileTypes: true });
        
        for (const entry of entries) {
            if (!entry.isDirectory()) continue;
            
            const projectPath = path.join(this.ohCodeRoot, entry.name);
            const bundleJsonPath = path.join(projectPath, 'bundle.json');
            
            // 检查是否是 OH 工程（包含 bundle.json）
            if (fs.existsSync(bundleJsonPath)) {
                try {
                    const bundleJson = JSON.parse(fs.readFileSync(bundleJsonPath, 'utf-8'));
                    projects.push({
                        name: entry.name,
                        path: projectPath,
                        subsystem: bundleJson.component?.subsystem || 'unknown',
                        component: bundleJson.component?.name || entry.name,
                        bundleJson: bundleJson
                    });
                } catch (error) {
                    Logger.warn(`[CodebaseIndexer] 解析 bundle.json 失败: ${projectPath}`);
                }
            }
        }

        return projects;
    }

    /**
     * 学习单个工程的代码模式
     */
    private async learnProject(project: OHProject): Promise<void> {
        Logger.info(`[CodebaseIndexer] 学习工程: ${project.name}`);

        // 1. 学习单元测试模式
        await this.learnUnitTests(project);

        // 2. 学习 Fuzz 测试模式
        await this.learnFuzzTests(project);

        // 3. 学习 BUILD.gn 模式
        await this.learnBuildConfigs(project);

        // 4. 学习代码结构模式
        await this.learnCodeStructure(project);

        // 5. 学习 Mock 模式
        await this.learnMockPatterns(project);
    }

    /**
     * 学习单元测试模式
     */
    private async learnUnitTests(project: OHProject): Promise<void> {
        const testDirs = [
            path.join(project.path, 'test', 'unittest'),
            path.join(project.path, 'test', 'unittests'),
            path.join(project.path, 'tests', 'unittest')
        ];

        for (const testDir of testDirs) {
            if (!fs.existsSync(testDir)) continue;

            // 递归查找所有测试文件
            const testFiles = this.findFiles(testDir, /.*_test\.cpp$/);
            
            // ⭐ 充分学习：不限制数量，学习所有测试文件
            const maxFiles = testFiles.length;  // 全部学习
            Logger.info(`[CodebaseIndexer]   - 发现 ${testFiles.length} 个测试文件，将全部学习`);
            
            for (const testFile of testFiles.slice(0, maxFiles)) {
                try {
                    const content = fs.readFileSync(testFile, 'utf-8');
                    const pattern = this.extractUnitTestPattern(content, testFile);
                    
                    if (pattern) {
                        this.knowledgeBase.addUnitTestPattern(project.name, pattern);
                    }
                } catch (error) {
                    Logger.warn(`[CodebaseIndexer] 读取测试文件失败: ${testFile}`);
                }
            }
        }
    }

    /**
     * 学习 Fuzz 测试模式
     */
    private async learnFuzzTests(project: OHProject): Promise<void> {
        const fuzzDirs = [
            path.join(project.path, 'test', 'fuzztest'),
            path.join(project.path, 'test', 'fuzzer'),
            path.join(project.path, 'tests', 'fuzztest')
        ];

        for (const fuzzDir of fuzzDirs) {
            if (!fs.existsSync(fuzzDir)) continue;

            // 查找所有 fuzzer 目录
            const fuzzerDirs = fs.readdirSync(fuzzDir, { withFileTypes: true })
                .filter(d => d.isDirectory() && d.name.endsWith('_fuzzer'))
                .map(d => path.join(fuzzDir, d.name));

            // ⭐ 充分学习：学习所有fuzzer
            Logger.info(`[CodebaseIndexer]   - 发现 ${fuzzerDirs.length} 个Fuzzer，将全部学习`);
            
            for (const fuzzerDir of fuzzerDirs) {
                try {
                    const pattern = await this.extractFuzzTestPattern(fuzzerDir);
                    if (pattern) {
                        this.knowledgeBase.addFuzzTestPattern(project.name, pattern);
                    }
                } catch (error) {
                    Logger.warn(`[CodebaseIndexer] 解析 fuzzer 失败: ${fuzzerDir}`);
                }
            }
        }
    }

    /**
     * 学习 BUILD.gn 配置模式
     */
    private async learnBuildConfigs(project: OHProject): Promise<void> {
        // 查找所有 BUILD.gn 文件
        const buildFiles = this.findFiles(project.path, /BUILD\.gn$/, 10); // ⭐ 增加深度到10
        
        // ⭐ 充分学习：学习所有BUILD.gn
        Logger.info(`[CodebaseIndexer]   - 发现 ${buildFiles.length} 个BUILD.gn，将全部学习`);

        for (const buildFile of buildFiles) {
            try {
                const content = fs.readFileSync(buildFile, 'utf-8');
                const config = this.extractBuildConfig(content, buildFile);
                
                if (config) {
                    this.knowledgeBase.addBuildConfig(project.name, config);
                }
            } catch (error) {
                Logger.warn(`[CodebaseIndexer] 读取 BUILD.gn 失败: ${buildFile}`);
            }
        }
    }

    /**
     * 学习代码结构模式
     */
    private async learnCodeStructure(project: OHProject): Promise<void> {
        const cppFiles = this.findFiles(project.path, /\.(cpp|cc)$/, 3);
        const headerFiles = this.findFiles(project.path, /\.(h|hpp)$/, 3);

        // 分析目录结构
        const structure = {
            hasIncludeDir: fs.existsSync(path.join(project.path, 'include')),
            hasSrcDir: fs.existsSync(path.join(project.path, 'src')),
            hasServicesDir: fs.existsSync(path.join(project.path, 'services')),
            hasInterfacesDir: fs.existsSync(path.join(project.path, 'interfaces')),
            cppFileCount: cppFiles.length,
            headerFileCount: headerFiles.length
        };

        this.knowledgeBase.addProjectStructure(project.name, structure);
    }

    /**
     * 学习 Mock 模式
     */
    private async learnMockPatterns(project: OHProject): Promise<void> {
        const testDirs = [
            path.join(project.path, 'test'),
            path.join(project.path, 'tests')
        ];

        for (const testDir of testDirs) {
            if (!fs.existsSync(testDir)) continue;

            // 查找 mock 目录
            const mockDir = path.join(testDir, 'mock');
            if (fs.existsSync(mockDir)) {
                const mockFiles = this.findFiles(mockDir, /\.(cpp|h)$/);
                
                for (const mockFile of mockFiles.slice(0, 3)) {
                    try {
                        const content = fs.readFileSync(mockFile, 'utf-8');
                        const pattern = this.extractMockPattern(content);
                        
                        if (pattern) {
                            this.knowledgeBase.addMockPattern(project.name, pattern);
                        }
                    } catch (error) {
                        Logger.warn(`[CodebaseIndexer] 读取 mock 文件失败: ${mockFile}`);
                    }
                }
            }
        }
    }

    /**
     * 提取单元测试模式
     */
    private extractUnitTestPattern(content: string, filePath: string): UnitTestPattern | null {
        // 提取测试类名
        const classMatch = content.match(/class\s+(\w+)\s*:\s*public\s+testing::Test/);
        if (!classMatch) return null;

        return {
            filePath,
            testClassName: classMatch[1],
            hasSetUpTestCase: content.includes('SetUpTestCase'),
            hasTearDownTestCase: content.includes('TearDownTestCase'),
            hasSetUp: content.includes('void SetUp()'),
            hasTearDown: content.includes('void TearDown()'),
            usesHWTEST_F: content.includes('HWTEST_F'),
            usesGMock: content.includes('gmock') || content.includes('EXPECT_CALL'),
            includes: this.extractIncludes(content),
            namespaces: this.extractNamespaces(content),
            testCaseCount: (content.match(/HWTEST_F/g) || []).length,
            exampleSnippet: this.extractFirstTestCase(content)
        };
    }

    /**
     * 提取 Fuzz 测试模式
     */
    private async extractFuzzTestPattern(fuzzerDir: string): Promise<FuzzTestPattern | null> {
        const fuzzerName = path.basename(fuzzerDir);
        const buildGnPath = path.join(fuzzerDir, 'BUILD.gn');
        const cppFile = path.join(fuzzerDir, `${fuzzerName}.cpp`);

        if (!fs.existsSync(buildGnPath) || !fs.existsSync(cppFile)) {
            return null;
        }

        const buildContent = fs.readFileSync(buildGnPath, 'utf-8');
        const cppContent = fs.readFileSync(cppFile, 'utf-8');

        return {
            fuzzerName,
            fuzzerDir,
            hasMessageParcel: cppContent.includes('MessageParcel'),
            hasFuzzedDataProvider: cppContent.includes('FuzzedDataProvider'),
            hasAccessTokenSetup: cppContent.includes('SetAccessTokenPermission'),
            hasStubImpl: cppContent.includes('StubImpl') || cppContent.includes('Stub>'),
            buildGnPattern: this.extractBuildConfig(buildContent, buildGnPath),
            includes: this.extractIncludes(cppContent),
            exampleSnippet: cppContent.substring(0, 500)
        };
    }

    /**
     * 提取 BUILD.gn 配置
     */
    private extractBuildConfig(content: string, filePath: string): BuildConfigPattern | null {
        return {
            filePath,
            hasOhosUnittest: content.includes('ohos_unittest'),
            hasOhosFuzztest: content.includes('ohos_fuzztest'),
            moduleOutPath: this.extractModuleOutPath(content),
            includeDirs: this.extractArrayField(content, 'include_dirs'),
            sources: this.extractArrayField(content, 'sources'),
            deps: this.extractArrayField(content, 'deps'),
            externalDeps: this.extractArrayField(content, 'external_deps'),
            defines: this.extractArrayField(content, 'defines'),
            hasPrivatePublic: content.includes('"private=public"'),
            imports: this.extractImports(content)
        };
    }

    /**
     * 提取 Mock 模式
     */
    private extractMockPattern(content: string): MockPattern | null {
        const classMatch = content.match(/class\s+(\w+Mock|\w+Impl)\s*:\s*public\s+(\w+)/);
        if (!classMatch) return null;

        return {
            mockClassName: classMatch[1],
            baseClassName: classMatch[2],
            usesGMock: content.includes('MOCK_METHOD'),
            overrideMethods: this.extractOverrideMethods(content),
            exampleSnippet: content.substring(0, 300)
        };
    }

    // ===== 辅助方法 =====

    private findFiles(dir: string, pattern: RegExp, maxDepth: number = 5): string[] {
        const results: string[] = [];
        
        const walk = (currentDir: string, depth: number) => {
            if (depth > maxDepth) return;
            if (!fs.existsSync(currentDir)) return;

            try {
                const entries = fs.readdirSync(currentDir, { withFileTypes: true });
                
                for (const entry of entries) {
                    // 跳过常见的忽略目录
                    if (entry.name === 'node_modules' || entry.name === '.git' || 
                        entry.name === 'out' || entry.name === 'dist') {
                        continue;
                    }

                    const fullPath = path.join(currentDir, entry.name);
                    
                    if (entry.isDirectory()) {
                        walk(fullPath, depth + 1);
                    } else if (pattern.test(entry.name)) {
                        results.push(fullPath);
                    }
                }
            } catch (error) {
                // 忽略权限错误
            }
        };

        walk(dir, 0);
        return results;
    }

    private extractIncludes(content: string): string[] {
        const includes: string[] = [];
        const lines = content.split('\n');
        
        for (const line of lines) {
            const match = line.match(/#include\s+[<"]([^>"]+)[>"]/);
            if (match) {
                includes.push(match[1]);
            }
        }
        
        return includes.slice(0, 20); // 最多20个
    }

    private extractNamespaces(content: string): string[] {
        const namespaces: string[] = [];
        const matches = content.matchAll(/namespace\s+(\w+)/g);
        
        for (const match of matches) {
            namespaces.push(match[1]);
        }
        
        return [...new Set(namespaces)];
    }

    private extractFirstTestCase(content: string): string {
        const match = content.match(/HWTEST_F\([^{]+\{[\s\S]{0,300}/);
        return match ? match[0] : '';
    }

    private extractModuleOutPath(content: string): string {
        const match = content.match(/module_out_path\s*=\s*"([^"]+)"/);
        return match ? match[1] : '';
    }

    private extractArrayField(content: string, fieldName: string): string[] {
        const regex = new RegExp(`${fieldName}\\s*=\\s*\\[([^\\]]+)\\]`, 's');
        const match = content.match(regex);
        
        if (!match) return [];
        
        const items: string[] = [];
        const itemMatches = match[1].matchAll(/"([^"]+)"/g);
        
        for (const m of itemMatches) {
            items.push(m[1]);
        }
        
        return items.slice(0, 20);
    }

    private extractImports(content: string): string[] {
        const imports: string[] = [];
        const matches = content.matchAll(/import\("([^"]+)"\)/g);
        
        for (const match of matches) {
            imports.push(match[1]);
        }
        
        return imports;
    }

    private extractOverrideMethods(content: string): string[] {
        const methods: string[] = [];
        const matches = content.matchAll(/(\w+)\([^)]*\)\s+override/g);
        
        for (const match of matches) {
            methods.push(match[1]);
        }
        
        return methods;
    }

    /**
     * 提取通用模式（跨项目分析）
     * 关键：提取跨工程通用的模式，而不是特定工程的代码
     */
    private async extractCommonPatterns(): Promise<void> {
        Logger.info('[CodebaseIndexer] 🔍 提取通用模式（跨工程分析）...');
        
        // 1. 分析最常用的依赖（出现在 50%+ 工程中）
        const commonDeps = this.knowledgeBase.getMostCommonDependencies();
        const highFreqDeps = commonDeps.filter((dep, idx) => {
            const count = this.knowledgeBase.getDependencyCount(dep);
            const projectCount = this.knowledgeBase.getProjectCount();
            return count >= projectCount * 0.3; // 出现在30%以上工程中
        });
        
        // 2. 分析最常用的 include
        const commonIncludes = this.knowledgeBase.getMostCommonIncludes();
        
        // 3. 分析最常用的 Mock 模式
        const commonMockPatterns = this.knowledgeBase.getMostCommonMockPatterns();
        
        // 4. 统计通用测试框架特征
        const frameworkStats = {
            hwtest_f_usage: this.knowledgeBase.countFeature('usesHWTEST_F'),
            gmock_usage: this.knowledgeBase.countFeature('usesGMock'),
            messageParcel_usage: this.knowledgeBase.countFeature('hasMessageParcel'),
            fuzzedDataProvider_usage: this.knowledgeBase.countFeature('hasFuzzedDataProvider')
        };
        
        // 5. 保存通用模式
        this.knowledgeBase.setCommonPatterns({
            commonDependencies: highFreqDeps,
            commonIncludes: commonIncludes.slice(0, 20),
            commonMockPatterns,
            frameworkStats,
            extractedAt: new Date().toISOString()
        });
        
        Logger.info(`[CodebaseIndexer] ✅ 通用依赖 (≥30%工程): ${highFreqDeps.slice(0, 10).join(', ')}`);
        Logger.info(`[CodebaseIndexer] ✅ 通用头文件: ${commonIncludes.slice(0, 5).join(', ')}`);
        Logger.info(`[CodebaseIndexer] ✅ HWTEST_F 使用率: ${frameworkStats.hwtest_f_usage.percentage}%`);
        Logger.info(`[CodebaseIndexer] ✅ MessageParcel 使用率: ${frameworkStats.messageParcel_usage.percentage}%`);
    }

    /**
     * 构建检索索引
     */
    private async buildIndex(): Promise<void> {
        Logger.info('[CodebaseIndexer] 构建检索索引...');
        await this.knowledgeBase.buildSearchIndex();
    }

    /**
     * 持久化知识库
     */
    private async saveKnowledgeBase(): Promise<void> {
        const savePath = path.join(__dirname, 'codebase-knowledge.json');
        await this.knowledgeBase.save(savePath);
        Logger.info(`[CodebaseIndexer] 知识库已保存: ${savePath}`);
    }

    /**
     * 打印学习摘要
     */
    private printSummary(): void {
        const summary = this.knowledgeBase.getSummary();
        
        Logger.info('\n==================== 学习摘要 ====================');
        Logger.info(`✅ 扫描工程数: ${summary.projectCount}`);
        Logger.info(`✅ 单元测试模式: ${summary.unitTestPatternCount}`);
        Logger.info(`✅ Fuzz测试模式: ${summary.fuzzTestPatternCount}`);
        Logger.info(`✅ BUILD.gn配置: ${summary.buildConfigCount}`);
        Logger.info(`✅ Mock模式: ${summary.mockPatternCount}`);
        Logger.info('================================================\n');
    }
}

// ===== 类型定义 =====

interface OHProject {
    name: string;
    path: string;
    subsystem: string;
    component: string;
    bundleJson: any;
}

interface UnitTestPattern {
    filePath: string;
    testClassName: string;
    hasSetUpTestCase: boolean;
    hasTearDownTestCase: boolean;
    hasSetUp: boolean;
    hasTearDown: boolean;
    usesHWTEST_F: boolean;
    usesGMock: boolean;
    includes: string[];
    namespaces: string[];
    testCaseCount: number;
    exampleSnippet: string;
}

interface FuzzTestPattern {
    fuzzerName: string;
    fuzzerDir: string;
    hasMessageParcel: boolean;
    hasFuzzedDataProvider: boolean;
    hasAccessTokenSetup: boolean;
    hasStubImpl: boolean;
    buildGnPattern: BuildConfigPattern | null;
    includes: string[];
    exampleSnippet: string;
}

interface BuildConfigPattern {
    filePath: string;
    hasOhosUnittest: boolean;
    hasOhosFuzztest: boolean;
    moduleOutPath: string;
    includeDirs: string[];
    sources: string[];
    deps: string[];
    externalDeps: string[];
    defines: string[];
    hasPrivatePublic: boolean;
    imports: string[];
}

interface MockPattern {
    mockClassName: string;
    baseClassName: string;
    usesGMock: boolean;
    overrideMethods: string[];
    exampleSnippet: string;
}

interface ProjectStructure {
    hasIncludeDir: boolean;
    hasSrcDir: boolean;
    hasServicesDir: boolean;
    hasInterfacesDir: boolean;
    cppFileCount: number;
    headerFileCount: number;
}

/**
 * 代码知识库
 */
class CodeKnowledgeBase {
    private unitTestPatterns: Map<string, UnitTestPattern[]> = new Map();
    private fuzzTestPatterns: Map<string, FuzzTestPattern[]> = new Map();
    private buildConfigs: Map<string, BuildConfigPattern[]> = new Map();
    private mockPatterns: Map<string, MockPattern[]> = new Map();
    private projectStructures: Map<string, ProjectStructure> = new Map();
    private commonPatterns: any = null;  // 跨工程通用模式

    addUnitTestPattern(projectName: string, pattern: UnitTestPattern) {
        if (!this.unitTestPatterns.has(projectName)) {
            this.unitTestPatterns.set(projectName, []);
        }
        this.unitTestPatterns.get(projectName)!.push(pattern);
    }

    addFuzzTestPattern(projectName: string, pattern: FuzzTestPattern) {
        if (!this.fuzzTestPatterns.has(projectName)) {
            this.fuzzTestPatterns.set(projectName, []);
        }
        this.fuzzTestPatterns.get(projectName)!.push(pattern);
    }

    addBuildConfig(projectName: string, config: BuildConfigPattern) {
        if (!this.buildConfigs.has(projectName)) {
            this.buildConfigs.set(projectName, []);
        }
        this.buildConfigs.get(projectName)!.push(config);
    }

    addMockPattern(projectName: string, pattern: MockPattern) {
        if (!this.mockPatterns.has(projectName)) {
            this.mockPatterns.set(projectName, []);
        }
        this.mockPatterns.get(projectName)!.push(pattern);
    }

    addProjectStructure(projectName: string, structure: ProjectStructure) {
        this.projectStructures.set(projectName, structure);
    }

    getMostCommonDependencies(): string[] {
        const depCounts = new Map<string, number>();
        
        for (const configs of this.buildConfigs.values()) {
            for (const config of configs) {
                for (const dep of config.externalDeps) {
                    depCounts.set(dep, (depCounts.get(dep) || 0) + 1);
                }
            }
        }
        
        return Array.from(depCounts.entries())
            .sort((a, b) => b[1] - a[1])
            .map(e => e[0]);
    }

    getMostCommonIncludes(): string[] {
        const includeCounts = new Map<string, number>();
        
        for (const patterns of this.unitTestPatterns.values()) {
            for (const pattern of patterns) {
                for (const include of pattern.includes) {
                    includeCounts.set(include, (includeCounts.get(include) || 0) + 1);
                }
            }
        }
        
        return Array.from(includeCounts.entries())
            .sort((a, b) => b[1] - a[1])
            .map(e => e[0]);
    }

    getMostCommonMockPatterns(): string[] {
        const patterns: string[] = [];
        
        for (const mockPatterns of this.mockPatterns.values()) {
            for (const pattern of mockPatterns) {
                patterns.push(pattern.mockClassName);
            }
        }
        
        return [...new Set(patterns)];
    }

    async buildSearchIndex(): Promise<void> {
        // TODO: 构建向量索引以支持语义搜索
        // 可以使用轻量级的本地向量库
    }

    async save(filePath: string): Promise<void> {
        const data = {
            unitTestPatterns: Array.from(this.unitTestPatterns.entries()),
            fuzzTestPatterns: Array.from(this.fuzzTestPatterns.entries()),
            buildConfigs: Array.from(this.buildConfigs.entries()),
            mockPatterns: Array.from(this.mockPatterns.entries()),
            projectStructures: Array.from(this.projectStructures.entries()),
            commonPatterns: this.commonPatterns,  // 保存通用模式
            savedAt: new Date().toISOString(),
            trainingProjectCount: this.projectStructures.size  // 记录训练集大小
        };
        
        fs.writeFileSync(filePath, JSON.stringify(data, null, 2), 'utf-8');
        Logger.info(`[CodeKnowledgeBase] 💾 知识库已保存（训练集: ${data.trainingProjectCount} 个工程）`);
    }

    async load(filePath: string): Promise<void> {
        if (!fs.existsSync(filePath)) {
            return;
        }

        const data = JSON.parse(fs.readFileSync(filePath, 'utf-8'));
        
        this.unitTestPatterns = new Map(data.unitTestPatterns);
        this.fuzzTestPatterns = new Map(data.fuzzTestPatterns);
        this.buildConfigs = new Map(data.buildConfigs);
        this.mockPatterns = new Map(data.mockPatterns);
        this.projectStructures = new Map(data.projectStructures);
        this.commonPatterns = data.commonPatterns;
        
        Logger.info(`[CodeKnowledgeBase] ✅ 已加载知识库: ${filePath}`);
        Logger.info(`[CodeKnowledgeBase] 📊 训练集工程数: ${data.trainingProjectCount || this.projectStructures.size}`);
        Logger.info(`[CodeKnowledgeBase] 🎯 知识可应用到任意 OpenHarmony 工程`);
    }

    getSummary() {
        return {
            projectCount: this.projectStructures.size,
            unitTestPatternCount: Array.from(this.unitTestPatterns.values()).reduce((sum, arr) => sum + arr.length, 0),
            fuzzTestPatternCount: Array.from(this.fuzzTestPatterns.values()).reduce((sum, arr) => sum + arr.length, 0),
            buildConfigCount: Array.from(this.buildConfigs.values()).reduce((sum, arr) => sum + arr.length, 0),
            mockPatternCount: Array.from(this.mockPatterns.values()).reduce((sum, arr) => sum + arr.length, 0)
        };
    }

    setCommonPatterns(patterns: any) {
        this.commonPatterns = patterns;
    }

    getCommonPatterns() {
        return this.commonPatterns;
    }

    getProjectCount(): number {
        return this.projectStructures.size;
    }

    getDependencyCount(dep: string): number {
        let count = 0;
        for (const configs of this.buildConfigs.values()) {
            for (const config of configs) {
                if (config.externalDeps.includes(dep)) {
                    count++;
                    break; // 每个项目只计数一次
                }
            }
        }
        return count;
    }

    countFeature(featureName: string): { count: number; total: number; percentage: number } {
        let count = 0;
        let total = 0;

        if (featureName === 'usesHWTEST_F' || featureName === 'usesGMock') {
            for (const patterns of this.unitTestPatterns.values()) {
                for (const pattern of patterns) {
                    total++;
                    if (pattern[featureName]) count++;
                }
            }
        } else if (featureName === 'hasMessageParcel' || featureName === 'hasFuzzedDataProvider' || featureName === 'hasStubImpl') {
            for (const patterns of this.fuzzTestPatterns.values()) {
                for (const pattern of patterns) {
                    total++;
                    if (pattern[featureName]) count++;
                }
            }
        }

        return {
            count,
            total,
            percentage: total > 0 ? Math.round((count / total) * 100) : 0
        };
    }

    /**
     * 检索相关的单元测试示例
     */
    public searchUnitTestExamples(context: {
        subsystem?: string;
        component?: string;
        keyword?: string;
    }): UnitTestPattern[] {
        const results: UnitTestPattern[] = [];
        
        for (const [projectName, patterns] of this.unitTestPatterns.entries()) {
            for (const pattern of patterns) {
                // 简单的关键词匹配
                if (context.keyword && pattern.testClassName.toLowerCase().includes(context.keyword.toLowerCase())) {
                    results.push(pattern);
                } else if (!context.keyword) {
                    results.push(pattern);
                }
            }
        }
        
        return results.slice(0, 3); // 返回前3个最相关的示例
    }

    /**
     * 检索相关的 Fuzz 测试示例
     */
    public searchFuzzTestExamples(context: {
        subsystem?: string;
        hasIPC?: boolean;
        keyword?: string;
    }): FuzzTestPattern[] {
        const results: FuzzTestPattern[] = [];
        
        for (const [projectName, patterns] of this.fuzzTestPatterns.entries()) {
            for (const pattern of patterns) {
                // 根据特征筛选
                if (context.hasIPC && pattern.hasMessageParcel) {
                    results.push(pattern);
                } else if (!context.hasIPC) {
                    results.push(pattern);
                }
            }
        }
        
        return results.slice(0, 3);
    }
}

